from fastapi import APIRouter, Header
from starlette.requests import Request

from model.db import Tb_Depart
from model.db.mapper.company_mapper import get_company_Bycode
from model.db.mapper.depart_mapper import add_depart, get_dapart_list, get_dapart_detail_list, update_depart_info
from model.params import RoleNameEnum
from model.params.depart_params import DepartInfoParam, UpdateDepartParam
from util import success_res, SuccessCode, objs_to_dict, error_res, ErrorCode
from util.access_token import parse_token
from util.public_func import need_serialize, obj_to_dict

depart_router = APIRouter(prefix="/depart", tags=['部门管理'])


@depart_router.post("", name="新增部门")
async def add(param: DepartInfoParam, request: Request, token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    depart = Tb_Depart(
        depart_name=param.depart_name,
        remark=param.remark,
        company_id=param.company_id
    )
    add_depart(depart)
    return success_res(obj_to_dict(depart), SuccessCode.POST)


@depart_router.get("/list", name="部门列表")
async def list(company_code: str):
    company = get_company_Bycode(company_code)
    departs = get_dapart_list(company.company_id);
    test = need_serialize(departs)
    return success_res({
        'departs': need_serialize(departs)
    }, SuccessCode.GET)


@depart_router.post("/allList", name="部门列表")
async def add(request: Request, token=Header("token")):
    companys = get_dapart_detail_list()
    return success_res(objs_to_dict(companys), SuccessCode.GET)


@depart_router.post('/update', name="更新部门")
async def company_list(update: UpdateDepartParam):
    add = update_depart_info(update.add, update.delete, update.update)
    return success_res({'add': objs_to_dict(add)}, SuccessCode.GET)
